package com.aididi.concurrent;

import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.*;
import java.util.Date;

/**
 * @Auther: xuzexiang
 * @Date: 2018-10-25 0025 22:50
 * @Description:    测试序列化和反序列化
 */
public class SerializableDemo {

    public static void main(String[] args) {
        new Thread().run();

        //Initializes The Object
        User user = new User();
        user.setName("hollis");
        user.setGender("male");
        user.setAge(23);
        user.setBirthday(new Date());
        System.out.println(user);

        //Write Obj to File
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("D:\\tempFile.txt"));
            oos.writeObject(user);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(oos);
        }

        //Read Obj from File
        File file = new File("D:\\tempFile.txt");
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(file));
            User newUser = (User) ois.readObject();
            System.out.println(newUser);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(ois);
            try {
                FileUtils.forceDelete(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}

class User implements Serializable {
private String name;
private int age;
private Date birthday;
private transient String gender;
private static final long serialVersionUID = -6849794470754667710L;

public String getName() {
        return name;
        }

public void setName(String name) {
        this.name = name;
        }

public int getAge() {
        return age;
        }

public void setAge(int age) {
        this.age = age;
        }

public Date getBirthday() {
        return birthday;
        }

public void setBirthday(Date birthday) {
        this.birthday = birthday;
        }

public String getGender() {
        return gender;
        }

public void setGender(String gender) {
        this.gender = gender;
        }

@Override
public String toString() {
        return "User{" +
        "name='" + name + '\'' +
        ", age=" + age +
        ", gender=" + gender +
        ", birthday=" + birthday +
        '}';
        }
}
